// Define fetchWrapper function
import showMsg from './showMessage'
const timeout = 10000
const request = async (url: string, options: RequestInit = {}): Promise<any> => {
  // Part 1: Add headers and attach auth token
  const headers = new Headers(options.headers || {})
  const token = localStorage.getItem('token')
  if (token) {
    headers.set('Authorization', `Bearer ${token}`)
  }
  let controller = new AbortController()
  let signal = controller.signal
  // Part 2: Fetch sends the request
  setTimeout(() => {
    controller.abort()
  }, timeout)
  try {
    const response = await fetch(url, {
      ...options,
      headers,
      signal: signal,
    })
    // Part 3: Handle the received response
    if (response.ok) {
      // If the status code is 200, convert data structure according to Content-Type
      const contentType = response.headers.get('Content-Type')
      if (contentType && contentType.includes('application/json')) {
        const data = await response.json()
        if (data.code === 200) {
          return data.data
        } else {
          throw data.message
        }
      } else if (contentType && contentType.includes('text/plain')) {
        return await response.text()
      } else {
        // Manage other Content-Type cases or when Content-Type is absent
      }
    } else {
      throw response
    }
  } catch (err) {
    if (err instanceof Response) {
      const data = await err.json()
      if (err.status === 500) {
        showMsg('服务器出现错误，请稍后重试', 'error')
      } else {
        showMsg(data.detail || '请求失败，请稍后重试', 'error')
      }
    } else if (err instanceof Error) {
      if (err.message.includes('aborted')) {
        showMsg('请求超时，请稍后重试', 'error')
      } else {
        showMsg('请求失败，请稍后重试', 'error')
      }
    } else if (typeof err === 'string') {
      showMsg(err, 'error')
    } else {
      showMsg('请求失败，请稍后重试', 'error')
    }
    return Promise.reject(err)
  }
}
export default request
